const http = require('http');
const url = require('url');
const fs = require('fs');

routes = {
    '/'(req, res) {
        res.end('关爱单身狗成长协会');
    },
    '/demo'(req, res) { 
        res.write(fs.readFileSync('./demo.html', 'utf-8'));
        res.end();
    },
    err(req, res, errCode) {
        res.writeHead(errCode, { 'Content-Type': 'text/html' });
        res.write(errCode.toString());
        res.end();
    }
};

http.createServer((req, res) => {
    let { pathname } = url.parse(req.url, true);
    let route = routes[pathname];
    try {
        return route ? route(req, res) : routes.err(req, res, 400);
    }
    catch (err) {
        console.error(err);
        routes.err(req, res, 500);
    }
}).listen(8080);